package main

import (
	"github.com/BurntSushi/toml"
	"github.com/kataras/iris"
	"github.com/ngaut/log"
	"server/backup/model"
	"github.com/garyburd/redigo/redis"
	"time"
	"sync"
	"fmt"
)

type Core struct {
	sync.Mutex
	startTime 		time.Time
	redisPool 		map[string]*redis.Pool
	config    		*Configuration
}

func (k *Core) bootstrap() {
	// log
	k.config.Log.Setting()

	// redis
	fmt.Println(k.config.Redis)

	for key, conf := range k.config.Redis {
		k.redisPool[key] = conf.redisPool()
	}

	// db
	// 目前只考虑主库情况
	if dbConfig, ok := k.config.Db["main"]; ok {
		model.InitMainDB(dbConfig.FormatDBConnection())
	} else {
		log.Fatalf("database connect error, check configuration")
	}
}

func (k *Core) GetBaseRedisPool() *redis.Pool {
	if pool, ok := k.redisPool["base"]; ok {
		return pool
	}
	return nil
}

// init default data
func (k *Core) initialize() {
	k.startTime = time.Now()
}

func (k *Core) start() {
	manager := NewBackup()
	manager.run(k)
}

func server() {
	config := loadConfiguration()
	bk := Core{
		config:    		&config,
		redisPool: 		make(map[string]*redis.Pool),
	}

	// 2. init
	bk.bootstrap()

	bk.initialize()

	// 3. start server
	bk.start()

	app := iris.New()
	app.Run(iris.Addr(bk.config.Http.GetAddr()))
}

func loadConfiguration() Configuration {

	// decode toml file
	configuration := newConfiguration()
	_, err := toml.DecodeFile(CONFIG_FILE, &configuration)
	if err != nil {
		panic(err.Error())
	}

	return configuration
}
